<?php
session_start();
require_once "../includes/common.php";
require_once BASE_PATH.'/class/Comments.class.php';
require_once BASE_PATH.'/class/User.class.php';
require_once "../islogin.php";

class CommentsApi {
    private $comments;


    public function __construct() {
        $this->comments = new Comments();
    }

    public function handleRequest() {
        if (!isset($_GET['type'])) {
            $this->respond(json_encode(['error' => '缺少 type 参数']));
            return;
        }

        //安全验证uid
        global $user_info; // 使用 global 关键字引用外部变量
        if($_POST['uid']){
            if ($_POST['uid']!=$user_info['message']['user_id']) {
                $this->respond(json_encode(['message' => 'uid error!']));
                return;
            }
        }

        switch ($_GET['type']) {
            case 'send':
                $this->send();
                break;
            case 'getpl':
                $this->getcomments();
                break;
            case 'udelpl':
                $this->udelpl();
                break;
            case 'delotherpl':
                $this->delotherpl();
                break;

            default:
                $this->respond(json_encode(['error' => '无效的 type 参数']));
                break;
        }
    }

    private function send() {
        $uid = $_POST['uid'] ?? '';
        $nid = $_POST['nid'] ?? '';
        $comment = $_POST['comment'] ?? '';
        //($user_id, $note_id, $comment
        $res = $this->comments->sendComments($uid,$nid,$comment);

        $this->respond($res);
    }
    private function getcomments() {
        $nid = $_POST['nid'] ?? '';
        $page = $_POST['page'] ?? 1;
        $limit = 12;        //每页12条
        $page = is_numeric($page) && $page > 0 ? intval($page) : 1;

        $res = $this->comments->getNoteComments($nid,$page,$limit);

        $this->respond($res);
    }
    private function udelpl() {
        $uid = $_POST['uid'] ?? '';
        $cid = $_POST['cid'] ?? '';
        //($user_id, $note_id, $comment
        $res = $this->comments->UserdeleteComments($uid,$cid);

        $this->respond($res);
    }
    private function delotherpl() {
        $uid = $_POST['uid'] ?? '';
        $cid = $_POST['cid'] ?? '';
        //($user_id, $note_id, $comment
        $res = $this->comments->deleteComments($uid,$cid);

        $this->respond($res);
    }



    private function respond($data) {
        header('Content-Type: application/json');
        echo $data;
        exit;
    }
}

$api = new CommentsApi();
$api->handleRequest();


